package com.xinshujia.test;

import org.eclipse.paho.client.mqttv3.*;

import java.util.Random;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-25 15:40       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 */
public class MyMqttClient {
    //MQTTurl
    private static String url = "tcp://192.168.3.6:1883";
    //MQTTid头
    private static String clientId = "mqtt_";
    //创建MQTT对象
    private static MqttCallback cb = new MqttCallback() {
        @Override
        public void connectionLost(Throwable throwable) {
            System.out.println("连接断开");
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            System.out.println("接收消息主题:" + topic);
            System.out.println("接收消息内容:" + new String(message.getPayload()));
            System.out.println("接收消息Qos:" + message.getQos());
            System.out.println("接收消息retained:" + message.isRetained());
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        }
    };

    public static void main(String[] args) throws MqttException {
        //注意id唯一
        MqttClient client = new MqttClient(url, clientId + new Random().nextInt(9000) + 1000);
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName("shangxiao");
        options.setPassword("shangxiao".toCharArray());
        client.setCallback(cb);
        client.connect(options);
        System.out.println("【接收】已开启订阅，等待消息");
        // 订阅主题 (接受此主题的消息) 更改为自己的订阅主题
        client.subscribe("warn_topic", 2);
    }
}
